// 1. 引入axios库
import axios from 'axios';
import moment from 'moment';

// 2. 配置微信API密钥
const APPID = 'wx81836bd3c07dc725'; 
const APPSECRET = '897be41a030111f1c3670b65c547cb28'; 

let access_token = '';
let expires_tme = moment();

// 3. 定义异步函数获取access_token
async function getAccessToken() {
    if (moment().isBefore(expires_tme)) {
        return access_token;
    }
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`;
    try {
        const response = await axios.get(url);
        const data = response.data;

        if (data.access_token) {
            console.log('Access Token:', data.access_token);
            access_token = data.access_token;
            expires_tme = moment().add(data.expires_in, 'seconds');
            return data.access_token;
        } else {
            console.error('Failed to get access token:', data);
            return '';
        }
    } catch (error) {
        console.error('Error fetching access token:', error);
        return '';
    }
}

async function getOpenId(code) {

    await getAccessToken();
    if (access_token == ''||access_token==null) {
        return { code: 0, msg: '获取access_token失败' };
    }
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code`;
    console.log('url:', url);
    try {
        let res = await axios.get(url);
        if (res) {
            if (res.data.openid) {
                return { code: 1, openid: res.data.openid };
            }
            else {
                return { code: 0, msg: res.data.errmsg };
            }
        }
    }
    catch (ex) {
        return { code: 0, msg: ex.message };
    }
}

export {getOpenId}

